import { deepClone } from "Yan/utils"
import { getDefaultFormConfig } from "Yan/utils/util"

/* 浅拷贝对象属性，obj2覆盖obj1 */
function overwriteObj(obj1, obj2) {
  Object.keys(obj2).forEach(prop => {
    obj1[prop] = obj2[prop]
  })
}
export default function createDesigner(vueInstance, designStatus = true, previewStatus = false) {
  const defaultFormConfig = deepClone(getDefaultFormConfig())
  return {
    vueInstance: vueInstance,
    designStatus: designStatus,
    previewStatus: previewStatus,
    formConfig: getDefaultFormConfig(),
    // 各字段的字典
    fieldLib: {},
    // 表单的树形结构
    fieldTree: [],
    uploadBase: '',
    // 获取表单模板
    getImportTemplate() {
      return {
        fieldLib: {},
        fieldTree: [],
        formConfig: deepClone(defaultFormConfig)
      }
    },
    // 加载导入的表单JSON
    loadFormJson(formJson) {
      let modifiedFlag = false
      if (formJson) {
        // this.formWidget.clearWidgetRefList()
        if (formJson.fieldLib) this.fieldLib = formJson.fieldLib
        if (formJson.fieldTree) this.fieldTree.push(...formJson.fieldTree)
        modifiedFlag = true
      }
      if (!!formJson && !!formJson.formConfig) {
        // this.formConfig = importObj.formConfig
        /* 用=赋值，会导致inject依赖注入的formConfig属性变成非响应式 */
        overwriteObj(this.formConfig, formJson.formConfig)
        modifiedFlag = true
      }
      // 通知其他组件
      if (modifiedFlag) this.emitEvent('form-json-imported', [])
      return modifiedFlag
    },
    clearDesigner() {
      this.fieldLib = {}
      this.fieldTree = []
      this.selectedId = null
      overwriteObj(this.formConfig, defaultFormConfig)
    },
    // 布局类型 输出
    getLayoutType() {
      return this.formConfig.layoutType || 'PC'
    },
    emitHistoryChange() { },
    // 用于兄弟组件发送事件
    emitEvent(evtName, evtData) {
      vueInstance.$emit(evtName, evtData)
    },
    // 用于兄弟组件接收事件
    handleEvent(evtName, callback) {
      vueInstance.$on(evtName, (data) => callback(data))
    },
  }
}
